/** @format */

import { defineConfig } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
import fs from 'fs';
import * as dotenv from 'dotenv';
import { resolve } from 'path';

// https://vitejs.dev/config/
export default defineConfig(() => {
  let envFile = `.env.${process.env.DEPLOY_ENV}`;

  const localEnvFile = `${envFile}.local`;
  if (fs.existsSync(resolve(__dirname, 'config/env', localEnvFile))) {
    envFile = localEnvFile;
  }
  envFile = fs.existsSync(resolve(__dirname, 'config/env', envFile))
    ? envFile
    : '.env.development';
  dotenv.config({ path: resolve(__dirname, 'config/env', envFile) });
  return {
    plugins: [uni()],
    server: {
      watch: {
        // 确保监听src目录的文件变化
        usePolling: true, // 使用轮询方式监听文件变化
        interval: 300, // 轮询间隔，单位毫秒
        ignored: ['**/node_modules/**', '**/.git/**'],
      },
      hmr: {
        // 启用热更新
        overlay: true,
        port: 24678, // 指定HMR端口
      },
    },
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
      },
    },
    // 优化构建配置
    optimizeDeps: {
      include: ['vue', '@dcloudio/uni-app'],
    },
    css: {
      preprocessorMaxWorkers: true,
      preprocessorOptions: {
        scss: {
          silenceDeprecations: ['legacy-js-api'],
        },
      },
    },
  };
});
